import React, { Component } from 'react';
import { messages } from "share/common";
import 'styles/data-center/hotel-report/hotel-report.scss';
import AdvanceSearch from 'components/advanced-search';
import HotelReportUtil from './hotel-report-util';
import upImage from 'images/data-center/upred@3x.png';
import downImage from 'images/data-center/downgreen3x.png';
import { Radio, Icon, message, Spin } from 'antd'
import { Chart, Geom, Axis, Tooltip, View, Legend, Coord, Label } from 'bizcharts';
import DataSet from '@antv/data-set';
import HotelReportServer from './hotel-report-server';

class HotelReport extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      loading2: false,
      loading3: false,
      dataSource:  /*HotelReportUtil.getTestData() || */[],
      dataSource2: /*HotelReportUtil.getTestData2() ||*/[],
      dataSource3: /*HotelReportUtil.getTestData3() ||*/[],
      searchForm: HotelReportUtil.getSearchForm(),
      baseData: {},
      backRate: 0.0,
      days: 0,
      chartWidth: 846,
      chartWidth2: 550,
      pinedList: [],
    }
    this.legendItems = [
      { value: messages('finance-7.key7')/*当月金额*/, marker: { symbol: 'square', fill: '#6FA4FF', radius: 5 } },
      { value: messages('finance-7.key8')/*同比金额*/, marker: { symbol: 'square', fill: '#50C0FF', radius: 5 } },
      { value: messages('finance-7.key9')/*同比*/, marker: { symbol: 'hyphen', stroke: '#FC9A28', radius: 5, lineWidth: 3 } },
      { value: messages('finance-7.key10')/*环比*/, marker: { symbol: 'hyphen', stroke: '#32CD91', radius: 5, lineWidth: 3 } },
    ];
    this.detailType = 'month';
    this.startReportType = 'AMOUNT'; // AMOUNT 消费金额  NIGHT 间夜
    this.cityReportType = 'AMOUNT'; // AMOUNT 消费金额  NIGHT 间夜
    this.paramsData = {};
  }

  handleSearch = (values) => {
    console.log(values)
    let month = [];
    let start = parseInt(values.startMonth);
    let end = parseInt(values.endMonth);
    if (end < start) {
      message.error(messages('finance-7.key13')/*结束月份不能小于开始月份*/);
      return;
    }
    for (let i = start; i <= end; i++) {
      month.push(i);
    }
    let params = {
      statisticByCompanyList: values.statisticByCompanyList,
      statisticByMonthList: month,
      statisticByYear: values.statisticByYear
    }
    this.paramsData = params;
    this.getReportBaseData(params)
    this.getReportDetailData(params)
    this.hotelStarDetailReport(params)
    this.hotelNightDetailReport(params)

  }

  getReportBaseData = (params) => {
    HotelReportServer(this).getReportBaseData(params).then(res => {
      if (res.data.body) {
        console.log(res)
        this.setState({
          baseData: res.data.body,
        });
      } else {
        this.setState({
          baseData: {},
          backRate: 0.0,
          days: 0,
        })
      }
    });
  }

  getReportDetailData = (params) => {
    let type = this.detailType === 'month' ? 'm' : 'q'; // m 月度 q 季度
    HotelReportServer(this).getReportDetailData(params, type).then(res => {
      console.log(res)
      this.setState({
        dataSource: res.data.body ? res.data.body.map(item => {
          if (type === 'q') {
            item.month = item[this.detailType];
          }
          return item;
        }) : [],
      });
    })
  }

  hotelStarDetailReport = (params) => {
    const data = Object.assign({}, params, {
      analysisType: this.startReportType
    })
    HotelReportServer(this).hotelStarDetailReport(data).then(res => {
      console.log(res)
      this.setState({dataSource2: res.data.body});
    })
  }

  hotelNightDetailReport = (params) => {
    const data = Object.assign({}, params, {
      analysisType: this.cityReportType
    })
    HotelReportServer(this).hotelNightDetailReport(data).then(res => {
      this.setState({dataSource3: res.data.body});
    })
  }

  onPinedListChange = (pinedList) => {
    this.setState({ pinedList });
  }

  onChangeRadio = (eve, type) => {
    if (type === 'detail') {
      this.detailType = eve.target.value;
      this.getReportDetailData(this.paramsData);
    }
    if (type === 'city') {// 城市
      this.cityReportType = eve.target.value;
      this.hotelNightDetailReport(this.paramsData);
    }
    if (type === 'star') { // 星级
      this.startReportType = eve.target.value;
      this.hotelStarDetailReport(this.paramsData);
    }
  }

  dealSource = (data, fields = ['totalPrice', 'yearByYearTotalPrice'], value = 'value') => {
    const ds = new DataSet();
    ds.setState('type', '');
    const dv = ds.createView().source(data);
    dv.transform({
      type: 'fold',
      fields: fields, // 展开字段集
      key: 'type', // key字段
      value: value, // value字段
    })
      .transform({
        type: 'filter',
        callback: (d) => {
          return d.type !== ds.state.type;
        }
      });
    return dv;
  }

  componentDidMount() {
    this.setState({
      chartWidth: this.chartRef.clientWidth - 56,
      chartWidth2: (this.chartRef2.clientWidth - 12) / 2,
    });
    this.advancedSearchRef.search();
  }

  render() {
    const { baseData, loading, backRate, days, searchForm, dataSource, dataSource2, dataSource3, chartWidth,
      loading2, loading3, chartWidth2, pinedList } = this.state;
    return (
      <div className='hotel-report-box'>
        <div className='search-box'>
          <AdvanceSearch
            tableName='hotel_report_chart_search'
            onSearch={this.handleSearch}
            title={messages('finance-7.key318')/*酒店管理报告*/}
            onRef={ref => this.advancedSearchRef = ref}
            getForm={form => this.advancedSearchFormRef = form}
            searchForm={searchForm}
            pinnedList={pinedList}
            onChangePinnedList={this.onPinedListChange}
            notLoadWhenMount
          />
        </div>
        <Spin spinning={loading}>
          <div className='hotel-total-box'>
            <div className='total-content'>
              <div className='total-content-one'>
                <div className='hotel-total-tile'>{messages('finance-7.key319')/*酒店总金额*/}</div>
                <div className='hotel-total-num'>{`${baseData.currency || ''} ${this.filterMoney(baseData.totalPrice, 2, true)}`}</div>
                <div className='hotel-compare-data border-none'>
                  <RenderCompare
                    name={messages('finance-7.key9')/*同比*/}
                    value={baseData.priceYearOnYearRatio}
                    haveImage={true}
                  />
                  <RenderCompare
                    name={messages('finance-7.key10')/*环比*/}
                    value={baseData.priceMonthOnMonthRatio}
                    haveImage={true}
                  />
                </div>
              </div>
              <div className='total-content-one' style={{ borderBottom: 0 }}>
                <div className='hotel-total-tile'>{messages('finance-7.key320')/*国内酒店*/}</div>
                <div className='hotel-compare-data border-none' style={{ marginTop: 12 }}>
                  <RenderCompare
                    name={messages('finance-7.key321')/*间夜均价（CNY）*/}
                    value={this.filterMoney(baseData.averageDomesticPrice, 2, true)}
                  />
                  <RenderCompare name={messages('finance-7.key322')/*间夜总数*/} value={baseData.totalDomesticNight || 0} />
                </div>
              </div>
              <div className='total-content-one' style={{ borderBottom: 0, paddingTop: 0 }}>
                <div className='hotel-total-tile'>{messages('finance-7.key323')/*国际酒店*/}</div>
                <div className='hotel-compare-data border-none' style={{ marginTop: 12 }}>
                  <RenderCompare
                    name={messages('finance-7.key321')/*间夜均价（CNY）*/}
                    value={this.filterMoney(baseData.averageForeignPrice, 2, true)}
                  />
                  <RenderCompare name={messages('finance-7.key322')/*间夜总数*/} value={baseData.totalForeignNight || 0} />
                </div>
              </div>
            </div>
            <div className='total-detail-chart' ref={chart => this.chartRef = chart}>
              <div className='chart-detail-title-box'>
                <div className='chart-detail-title'>{messages('finance-7.key324')/*酒店逐月消费*/}</div>
                <Radio.Group
                  onChange={(eve) => { this.onChangeRadio(eve, 'detail') }}
                  defaultValue="month"
                  buttonStyle="solid"
                  size="small"
                >
                  <Radio.Button value="month">{messages('finance-7.key21')/*月度*/}</Radio.Button>
                  <Radio.Button value="quarter">{messages('finance-7.key22')/*季度*/}</Radio.Button>
                </Radio.Group>
              </div>
              <div className='chart-detail-title-box'>
                <div className='tooltip' style={{ textAlign: 'left' }}>{messages('common.amount')/*金额*/}</div>
                <div className='tooltip'>{messages('finance-7.key23')/*比率*/}</div>
              </div>
              <div style={{ width: '100%' }}>
                <Chart
                  height={308}
                  width={chartWidth}
                  padding="auto"
                  data={this.dealSource(dataSource)}
                >
                  <Legend
                    custom
                    clickable={false}
                    allowAllCanceled
                    items={this.legendItems} />
                  <Tooltip />
                  <View data={this.dealSource(dataSource)}>
                    <Axis name='month' />
                    <Axis name='value' />
                    <Geom
                      tooltip={['type*value', (type, value) => { // array
                        let name = type === 'totalPrice' ? messages('finance-7.key24')/*当月总金额*/ : messages('finance-7.key8')/*同比金额*/
                        return {
                          name,
                          value: value || '-'
                        }
                      }]}
                      type='interval'
                      position={`month*value`}
                      color={['type', (value) => {
                        if (value === 'totalPrice') {
                          return '#6FA4FF';
                        }
                        if (value === 'yearByYearTotalPrice') {
                          return '#50C0FF';
                        }
                      }]}
                      adjust={[{
                        type: 'dodge',
                        marginRatio: 1 / 5,
                      }]}
                    />
                  </View>
                  <View data={this.dealSource(dataSource, ['monthByMonthTotalPriceRatio', 'yearByYearTotalPriceRatio'], 'rate')}>
                    <Axis name='rate' position='right' label={
                      {
                        formatter(text, item, index) {
                          return `${text}%`;
                        }
                      }
                    } />
                    <Geom
                      tooltip={['type*rate', (type, value) => { // array
                        let name = type === 'monthByMonthTotalPriceRatio' ? messages('finance-7.key10')/*环比*/ : messages('finance-7.key9')/*同比*/
                        return {
                          name,
                          value: value ? value + '%' : messages('common.empty.text')/*暂无数据*/
                        }
                      }]}
                      type='line'
                      position={`month*rate`}
                      color={['type', (value) => {
                        if (value === 'monthByMonthTotalPriceRatio') {
                          return '#32CD91';
                        }
                        if (value === 'yearByYearTotalPriceRatio') {
                          return '#FC9A28';
                        }
                      }]}
                      adjust={[{
                        type: 'dodge',
                        marginRatio: 0,
                      }]}
                    />
                    <Geom
                      tooltip={['type*rate', (type, value) => { // array
                        let name = type === 'monthByMonthTotalPriceRatio' ? messages('finance-7.key10')/*环比*/ : messages('finance-7.key9')/*同比*/
                        return {
                          name,
                          value: value ? value + '%' :  messages('common.empty.text')/*暂无数据*/
                        }
                      }]}
                      type='point'
                      position={`month*rate`}
                      color={['type', (value) => {
                        if (value === 'monthByMonthTotalPriceRatio') {
                          return '#32CD91';
                        }
                        if (value === 'yearByYearTotalPriceRatio') {
                          return '#FC9A28';
                        }
                      }]}
                      adjust={[{
                        type: 'dodge',
                        marginRatio: 0,
                      }]}
                    />
                  </View>
                </Chart>
              </div>
            </div>
          </div>
        </Spin>
        <div className='hotel-quota'>
          <div className='total-content-one'>
            <div className='hotel-total-tile'>{messages('finance-7.key325')/*酒店指标*/}</div>
            <div style={{ display: 'flex' }}>
              <RenderQuota name={messages('finance-7.key326')/*一线城市间夜均价*/} prefix='CNY' value={this.filterMoney(baseData.averageFirstCitiesPrice, 2, true)} />
              <RenderQuota name={messages('finance-7.key327')/*非一线城市间夜均价*/} prefix='CNY' value={this.filterMoney(baseData.averageSecondCitiesPrice, 2, true)} />
              <RenderQuota name={messages('finance-7.key328')/*一线城市协议酒店间夜比例*/} value={baseData.totalFirstCitiesPolicyRate} />
              <RenderQuota name={messages('finance-7.key329')/*非一线城市协议酒店间夜比例*/} value={baseData.totalSecondCitiesPolicyRate} />
            </div>
          </div>
        </div>
        <div className='hotel-star-box' ref={chart => this.chartRef2 = chart}>
          <Spin spinning={loading2}>
            <div className='star-one' style={{width: chartWidth2+12}}>
              <div className='chart-detail-title-box'>
                <div className='chart-detail-title'>{messages('finance-7.key330')/*星级分布*/}</div>
                <Radio.Group
                  onChange={(eve)=>{this.onChangeRadio(eve,'star')}}
                  defaultValue={'AMOUNT'}
                  buttonStyle="solid"
                  size="small"
                >
                  <Radio.Button value={'AMOUNT'}>{messages('finance-7.key331')/*消费金额*/}</Radio.Button>
                  <Radio.Button value={'NIGHT'}>{messages('finance-7.key332')/*间夜*/}</Radio.Button>
                </Radio.Group>
              </div>
              <Chart
                style={{paddingLeft: '9.5%'}}
                data={dataSource2}
                forceFit
                padding="auto"
                height={344}>
                <Coord type="theta" radius={0.75}/>
                <Axis name='amountRatio'/>
                <Legend position="left-center"/>
                <Tooltip showTitle={false} />
                <Geom
                  style={{
                    lineWidth: 2,
                    stroke: '#fff',
                  }}
                  tooltip={[
                    "star*statisticDate*totalAmount*amountRatio*totalNight*currency",
                    (star, statisticDate, totalAmount, amountRatio, totalNight, currency ) => {

                      return {
                        name: star,
                        value: `<div>
                                <div>${statisticDate}</div>
                                <div>${star}</div>
                                <div>${messages('finance-7.key333')/*间夜数*/}: ${totalNight}</div>
                                <div>${messages('common.total.amount')/*总金额*/}: ${currency} ${totalAmount}</div>
                                <div>${messages('finance-7.key334')/*间夜占比*/}: ${amountRatio}%</div>
                             </div>`
                      };
                    }
                  ]}
                  type="intervalStack"
                  position="amountRatio"
                  color="star">
                  <Label
                    content="amountRatio"
                    offset={-40}
                    formatter={(val) => {
                      return val+'%';
                    }}
                  />
                </Geom>
              </Chart>
              {
                dataSource2.length <= 0 && (
                  <div className='no-have-data' style={{position: 'absolute', top: 200, left: '40%'}}>
                    <Icon className='img-icon' type="folder-open" />
                    {messages('common.empty.text')/*暂无数据*/}
                  </div>
                )
              }
            </div>
          </Spin>
          <Spin spinning={loading3}>
            <div className='star-two' style={{width: chartWidth2}}>
              <div className='chart-detail-title-box'>
                <div className='chart-detail-title'>{messages('finance-7.key335')/*酒店前五城市分析*/}</div>
                <Radio.Group
                  onChange={(eve)=>{this.onChangeRadio(eve,'city')}}
                  defaultValue={'AMOUNT'}
                  buttonStyle="solid"
                  size="small"
                >
                  <Radio.Button value={'AMOUNT'}>{messages('finance-7.key331')/*消费金额*/}</Radio.Button>
                  <Radio.Button value={'NIGHT'}>{messages('finance-7.key332')/*间夜*/}</Radio.Button>
                </Radio.Group>
              </div>
              <Chart
                style={{paddingLeft: '9.5%'}}
                data={dataSource3}
                forceFit
                padding="auto"
                height={344}>
                <Coord type="theta" radius={0.75}/>
                <Axis name='amountRatio'/>
                <Legend position="left-center" name="cityName"/>
                <Tooltip showTitle={false} />
                <Geom
                  style={{
                    lineWidth: 2,
                    stroke: '#fff',
                  }}
                  tooltip={[
                    "cityName*statisticDate*totalAmount*amountRatio*totalNight*currency",
                    (cityName, statisticDate, totalAmount, amountRatio, totalNight, currency ) => {

                      return {
                        name: cityName,
                        value: `<div>
                                <div>${statisticDate}</div>
                                <div>${cityName}</div>
                                <div>${messages('finance-7.key333')/*间夜数*/}: ${totalNight}</div>
                                <div>${messages('common.total.amount')/*总金额*/}: ${currency} ${totalAmount}</div>
                                <div>${messages('finance-7.key334')/*间夜占比*/}: ${amountRatio}%</div>
                             </div>`
                      };
                    }
                  ]}
                  type="intervalStack"
                  position="amountRatio"
                  color="cityName">
                  <Label
                    content="amountRatio"
                    offset={-40}
                    formatter={(val) => {
                      return val+'%';
                    }}
                  />
                </Geom>
              </Chart>
              {
                dataSource3.length <= 0 && (
                  <div className='no-have-data' style={{position: 'absolute', top: 200, left: '40%'}}>
                    <Icon className='img-icon' type="folder-open" />
                    {messages('common.empty.text')/*暂无数据*/}
                  </div>
                )
              }
            </div>
          </Spin>
        </div>
      </div>
    )
  }
}

const RenderCompare = function ({ name, value, haveImage }) {
  let imgUrl = haveImage && value ? value > -1 ? upImage : downImage : '';
  if (haveImage) {
    value = `${value || 0}%`;
  }
  return (
    <div className='tong-compare' style={{ border: 'none' }}>
      <div className='tong-font'>{name}</div>
      <div className='tong-num'>
        {value}
        {imgUrl && <img className='tip-image-size' src={imgUrl} />}
      </div>
    </div>
  )
}

const RenderQuota = function ({ name, value, num, isRadio, onChangeRadio, prefix }) {
  let sty = { marginTop: 12, width: '25%' };
  if (num && num > 0) {
    sty.paddingLeft = 20;
  }
  prefix && value && (prefix = <span style={{ marginRight: '5px' }}>{prefix}</span>)
  if (!value) {
    prefix = ''
    value = (
      <div className='no-have-data'>
        <Icon className='img-icon' type="folder-open" />
        {messages('common.empty.text')/*暂无数据*/}
      </div>
    )
  }
  return (
    <div className='hotel-compare-data' style={sty}>
      <div className='tong-compare'>
        <div className='tong-font'>
          {name}
          {
            isRadio && (
              <Radio.Group
                onChange={(eve) => { onChangeRadio && onChangeRadio(eve) }}
                defaultValue="in"
                buttonStyle="solid"
                size="small"
              >
                <Radio.Button value="in">{messages('finance-7.key32')/*国内*/}</Radio.Button>
                <Radio.Button value="out">{messages('finance-7.key33')/*国际*/}</Radio.Button>
              </Radio.Group>
            )
          }
        </div>
        <div className='hotel-total-num' style={{ lineHeight: '40px', marginTop: 4 }}>
          {prefix}{value}
        </div>
      </div>
    </div>
  )
}



export default HotelReport
